#!/bin/bash

# 机器人创新实验室官网 - CentOS 部署脚本
# 适用于阿里云 CentOS 系统

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 项目配置
PROJECT_NAME="lab-web"
PROJECT_DIR="/var/www/$PROJECT_NAME"
BACKUP_DIR="/var/backups/$PROJECT_NAME"
NGINX_CONFIG="/etc/nginx/conf.d/$PROJECT_NAME.conf"

echo -e "${GREEN}=== 机器人创新实验室官网部署脚本 ===${NC}"

# 检查是否为root用户
if [[ $EUID -ne 0 ]]; then
   echo -e "${RED}此脚本需要root权限运行${NC}"
   exit 1
fi

# 函数：打印状态
print_status() {
    echo -e "${YELLOW}$1${NC}"
}

print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

# 1. 更新系统
print_status "更新系统..."
yum update -y

# 2. 安装必要软件
print_status "安装必要软件..."

# 安装Node.js 18.x
if ! command -v node &> /dev/null; then
    print_status "安装 Node.js 18.x..."
    curl -fsSL https://rpm.nodesource.com/setup_18.x | bash -
    yum install -y nodejs
else
    print_success "Node.js 已安装"
fi

# 安装 PM2
if ! command -v pm2 &> /dev/null; then
    print_status "安装 PM2..."
    npm install -g pm2
else
    print_success "PM2 已安装"
fi

# 安装 Nginx
if ! command -v nginx &> /dev/null; then
    print_status "安装 Nginx..."
    yum install -y epel-release
    yum install -y nginx
else
    print_success "Nginx 已安装"
fi

# 安装 Git
if ! command -v git &> /dev/null; then
    print_status "安装 Git..."
    yum install -y git
else
    print_success "Git 已安装"
fi

# 3. 创建项目目录
print_status "创建项目目录..."
mkdir -p $PROJECT_DIR
mkdir -p $BACKUP_DIR
mkdir -p /var/log/$PROJECT_NAME

# 4. 设置防火墙
print_status "配置防火墙..."
systemctl start firewalld
systemctl enable firewalld
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --permanent --add-port=3000/tcp
firewall-cmd --reload

# 5. 启动服务
print_status "启动系统服务..."
systemctl enable nginx
systemctl start nginx

# 6. 创建日志目录
mkdir -p $PROJECT_DIR/logs

print_success "系统环境准备完成！"

echo ""
echo -e "${GREEN}=== 下一步操作指南 ===${NC}"
echo "1. 将项目代码上传到: $PROJECT_DIR"
echo "2. 在项目目录中运行: npm install"
echo "3. 构建项目: npm run build"
echo "4. 配置 Nginx（参考 nginx-centos.conf）"
echo "5. 使用 PM2 启动应用: npm run pm2"
echo ""
echo -e "${YELLOW}部署路径: $PROJECT_DIR${NC}"
echo -e "${YELLOW}备份路径: $BACKUP_DIR${NC}"
echo -e "${YELLOW}日志路径: /var/log/$PROJECT_NAME${NC}"

# 7. 创建项目部署脚本
cat > "$PROJECT_DIR/update.sh" << 'EOF'
#!/bin/bash

# 项目更新脚本
PROJECT_DIR="/var/www/lab-web"
BACKUP_DIR="/var/backups/lab-web"

cd $PROJECT_DIR

# 备份当前版本
echo "备份当前版本..."
cp -r $PROJECT_DIR "$BACKUP_DIR/backup-$(date +%Y%m%d-%H%M%S)"

# 更新代码（如果使用 Git）
if [ -d ".git" ]; then
    echo "更新代码..."
    git pull origin main
fi

# 安装依赖
echo "安装/更新依赖..."
npm install --production

# 构建项目
echo "构建项目..."
npm run build

# 重启应用
echo "重启应用..."
npm run pm2:restart

echo "更新完成！"
EOF

chmod +x "$PROJECT_DIR/update.sh"

print_success "部署脚本创建完成！"